import re
import json
from bs4 import BeautifulSoup
from ..utils.logger import logger
from ..utils.config_reader import read_util
from ..utils.crypto_utils import server_utils


class BackendUser:

    @staticmethod
    def get_user_info_id(mobile_phone, return_full_resp=False):
        """
        发送请求获取用户信息并解析页面以提取用户 ID。
        """
        logger.info("------获取用户id------")
        try:
            params = {"mobilePhone": mobile_phone}
            response = server_utils.get_request(url="/userInfo/list.html", params=params)
            if response:
                if return_full_resp:
                    return response
                soup = BeautifulSoup(response, 'html.parser')
                span_element = soup.find('span', id='m-switch-0')
                if span_element:
                    onclick_value = span_element.get('onclick', '')
                    match = re.search(r"permissions\(this,'([^']*)'", onclick_value)
                    if match:
                        return match.group(1)
        except Exception as e:
            server_utils.handle_exception(e, "获取用户信息id失败或响应无效。")

    @staticmethod
    def get_user_info_rsNo(mobile_phone, return_full_resp=False):
        """
        发送请求获取用户信息并解析页面以提取用户 rsNo。
        """
        try:
            params = {"mobilePhone": mobile_phone}
            response = server_utils.get_request(url="/userInfo/list.html", params=params)
            values = []
            if response:
                if return_full_resp:
                    return response
                soup = BeautifulSoup(response, 'html.parser')
                # 查找所有的 onclick 属性值
                divs = soup.find_all('div', attrs={'class': 'item-btn-box'})
                if divs:
                    for div in divs:
                        onclick_value = div.get('onclick', '')
                        # 匹配 toaddorupdate 函数及其参数
                        match = re.search(r"toaddorupdate\('([^']*)'\s*,\s*'([^']*)'\)", onclick_value)
                        if match:
                            values.append(match.group(1))  # 添加第一个参数值
                            return values[0]
        except Exception as e:
            server_utils.handle_exception(e, "获取用户信息rsNo失败或响应无效。")

    @staticmethod
    def reset_user_password(user_id):
        """
        重置用户密码。
        """
        try:
            data = {"id": user_id}
            return server_utils.post_request(url="/userInfo/resetPassword.html", data=data).json()
        except Exception as e:
            server_utils.handle_exception(e, "重置用户密码失败")

    @staticmethod
    def update_user_phone(rs_no_value, username, mobile_phone):
        """
        修改用户手机号。
        """
        try:
            data = {"rsNo": rs_no_value, "userName": username, "mobilePhone": mobile_phone}
            return server_utils.post_request(url="/userInfo/updateMobilePhone.html", data=data).json()
        except Exception as e:
            server_utils.handle_exception(e, "修改用户手机号失败")

    @staticmethod
    def user_sms_code(mobile_phone):
        """
        获取用户短信验证码
        """
        logger.info("------查询用户短信验证码------")
        try:
            params = {"mobilePhone": mobile_phone}
            response = server_utils.get_request(url="/smsInfo/list.html", params=params)
            # 创建 BeautifulSoup 对象
            soup = BeautifulSoup(response, 'html.parser')
            # 查找第一个包含 "您的验证码是:" 的 <td> 标签
            target_td = soup.find('td', text=re.compile(r'您的验证码是.*'))

            # 提取验证码后面的数字
            if target_td:
                # 使用正则提取验证码数字
                verification_code = re.search(r'您的验证码是：\s*(\d+)', target_td.text)
                if verification_code:
                    return verification_code.group(1)  # 返回验证码
        except Exception as e:
            server_utils.handle_exception(e, "获取用户短信验证码失败")

    @staticmethod
    def add_sms_white(mobile_phone):
        """
        添加短信白名单
        """
        try:
            data = {"id": "", "mobilePhone": mobile_phone, "_validator_ajaxsubmit": True}
            return server_utils.post_request(url="/smsWhiteList/addorupdate.html", data=data).json()
        except Exception as e:
            server_utils.handle_exception(e, "添加短信白名单失败")

    @staticmethod
    def orders_get_userinfo_id(ids):
        """
        根据用户id，查询用户对应的交易编码号
        """
        logger.info("------获取用户交易编码号------")
        try:
            data_dict = {"ids": ids}
            # logger.debug(type(data_dict))
            return server_utils.post_request(url=f"/orders/getuserinfoid", data=data_dict).json()
        except Exception as e:
            server_utils.handle_exception(e, "查询用户对应的交易编码号失败")

    @staticmethod
    def bind_customer():
        """
        给用户绑定客服
        """
        logger.info("------绑定客服------")
        try:
            data_dict = {
                'rsNo': read_util.read_data()['app_uid'],
                'showType': 1,
                'sysUserId': '9869A106C46CF663E65BF75717D1AF417D8A2FBBCD42185F365E03EA27C323248F1C90015D0DE989'

            }
            return server_utils.post_request(url=f"/userInfo/updateUser.html", data=data_dict).json()
        except Exception as e:
            server_utils.handle_exception(e, "绑定客服失败")


backend_user = BackendUser()
